<template>
  <el-header
    class="header"
    style="min-width: 1200px"
  >
    <div class="platform-logo">
      <img
        v-if="isLianHai"
        src="@/assets/logo1.png"
        alt=""
        srcset=""
      >
      <el-cascader
        v-model="selectTree"
        :options="tableData"
        :props="props"
        :show-all-levels="false"
        @change="handleChange"
      >
        <template #default="{ data }">
          <el-icon style="margin-right:10px;">
            <OfficeBuilding />
          </el-icon>
          <span>{{ data.name }}</span>
        </template>
      </el-cascader>
    </div>
    <div class="func-area">
      <div
        class="func-toleft func-btn"
        @click="toLeft"
      >
        <img
          src="@/assets/menu/zuo.png"
          alt=""
          srcset=""
        >
      </div>
      <div
        id="func-tab-div"
        class="func-tab-div"
      >
        <ul
          id="func-tab"
          ref="funcTab"
          class="func-tab"
        >
          <li
            v-for="(i, index) in tabList"
            :class="defaultActive.includes(i) ? 'active' : ''"
          >
            <p @click="toUrl(i)">
              {{ getName(i) }}
            </p>
            <el-icon
              v-if="tabList.length > 1"
              @click="sliceTab(i, index)"
            >
              <Close />
            </el-icon>
          </li>
        </ul>
      </div>
      <div
        class="func-toright func-btn"
        @click="toRight"
      >
        <img
          src="@/assets/menu/you.png"
          alt=""
          srcset=""
        >
      </div>
      <div class="func-close func-btn">
        <img
          src="@/assets/menu/xia.png"
          alt=""
          srcset=""
        >
        <ul class="func-contextmenu">
          <li @click="closeOtherLeft">
            关闭左边菜单栏
          </li>
          <li @click="closeOtherRight">
            关闭右边菜单栏
          </li>
          <li @click="closeOther">
            关闭其他菜单栏
          </li>
        </ul>
      </div>
    </div>

    <div class="toolbar">
      <div
        class="tool-icon"
      >
        <FileExportNoticeCenter />
      </div>

      <div
        class="tool-icon"
        style="width:40px;"
      >
        <MessageCenter />
      </div>
      <!-- <div class="tomerchant" v-if="condition('MERCHANT')">
        <el-icon @click="toRoute('MERCHANT')">
          <home-filled/>
        </el-icon>
      </div>
      <div v-if="condition2()"
           class="menu-center"
           :class="{ active: isShowCenterMenu }"
           @click.stop.prevent="isShowCenterMenu = !isShowCenterMenu">
            <span class="el-dropdown-link">
              {{ "应用中心" }}
              <el-icon v-if="!isShowCenterMenu"><arrow-down/></el-icon>
              <el-icon v-else><arrow-up/></el-icon>
            </span>
      </div> -->
      <el-dropdown>
        <span class="el-dropdown-link">
          {{ username }}
          <el-icon>
            <arrow-down />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-if="!isBindWechat"
              @click="_showWechatBindDialog"
            >
              <i class="el-icon-switch-button" /> 绑定微信
            </el-dropdown-item>
            <el-dropdown-item
              v-else
              @click="unbindWechatConfirm({ id: store.state.user.userId })"
            >
              <i class="el-icon-switch-button" /> 解绑微信
            </el-dropdown-item>
            <el-dropdown-item @click.left="isShowChangePassword = true">
              <i class="el-icon-switch-button" /> 修改密码
            </el-dropdown-item>
            <el-dropdown-item @click.left="exit">
              <i class="el-icon-switch-button" /> 退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- <main-center-menu v-model:show="isShowCenterMenu"></main-center-menu> -->

    <change-password v-model:show="isShowChangePassword" />

    <bind-wechat
      v-model:show="isShowBindWechat"
      :row-data="currentUserInfo"
      :proactive-pop="proactivePopBindWechat"
      @bind-finished="handleBindWechatFinished"
    />
  </el-header>
</template>
<script lang="ts" setup>
import { Ref } from "vue";
import { ElMessage } from "element-plus";

import { treeTolistTree } from "@/utils";

import { useHeader } from "@/compositions/main/useHeader";
import { usePermission } from "@/compositions/main/usePermission";
import { useMenu } from "@/compositions/main/useMenu";
import { useCenterMenu } from "@/compositions/main/useCenterMenu";
import { useBindWechat } from "@/views/organization/compositions/useBindWechat";
import MessageCenter from '@/components/messageCenter/index.vue';
import ChangePassword from "@/views/passport/components/ChangePassword.vue";
import BindWechat from "@/views/organization/components/staff/BindWechat.vue";
import {
  queryTree
} from "@/api/orgManage";
const { title, username, exit } = useHeader({ loadTitle: true })
const { condition2, condition } = usePermission()
const { toRoute, defaultActive } = useMenu()
const { isShowCenterMenu } = useCenterMenu()
const isShowChangePassword: Ref<boolean> = ref(false)
const store = useStore()
const router = useRouter()
const elementDiv = ref()//外div
const element = ref()//内div
const currentPage = ref(1)//当前在第几页
const allPage = ref(0)//共多少页
const selectTree = computed(() => {
  return store.state.insId.insId
})
const handleChange = (value: any) => {
  store.commit('SETGLOBALINSID', value[value.length - 1])
  // setTimeout(()=>{
  //   window.location.reload()
  // },1000)
}
const tabList = computed(() => {
  return store.state.bookList.bookList?.[store.state.user.currentService] ?? []
})
watch(defaultActive, (val) => {
  if (store.state.bookList.bookList[store.state.user.currentService]?.includes(val)) {
    getLeft()
  }
})
const getLeft = () => {
  if (elementDiv.value) {
    const clientWidthDiv = elementDiv.value.clientWidth;
    const currentWidth = tabList.value.indexOf(defaultActive.value) * 142 + 142
    currentPage.value = Math.ceil(currentWidth / clientWidthDiv)
    if (currentPage.value > 1) {
      element.value.style.left = -(elementDiv.value.clientWidth * (currentPage.value - 1)) + 'px'
    } else {
      element.value.style.left = 0 + 'px'
    }
  }
}
const toUrl = (item: string) => {
  router.push(item)
}
const sliceTab = (item: string, index: number) => {

  if (tabList.value.length > 1) {
    store.commit("SLICETAB", {
      index: index,
      length: 1,
      service: store.state.user.currentService
    })
    router.replace(tabList.value[index - 1])
  } else {
    router.replace(tabList.value[0])
  }

}
const getName = (item: string) => {
  let aa: any = []
  store.state.user.allPermission.forEach(ele => {
    if (ele.serviceType == store.state.user.currentService) {
      aa = ele.permissionLayer
    }
  })
  const bb = treeTolistTree(aa)
  let name = ''
  if (bb.length > 0) {
    bb.forEach(ele => {
      if (ele.frontRouter == item) {
        name = ele.name
      }
    })
  }
  return name
}
const toLeft = () => {
  if (currentPage.value == 1) {
    element.value.style.left = '0px'
  } else {
    --currentPage.value
    element.value.style.left = -(elementDiv.value.clientWidth * (currentPage.value - 1)) + 'px'
  }
}
const toRight = () => {
  const clientWidth = element.value.clientWidth;
  const clientWidthDiv = elementDiv.value.clientWidth;
  allPage.value = Math.ceil(clientWidth / clientWidthDiv)
  if (currentPage.value < allPage.value) {
    element.value.style.left = -(elementDiv.value.clientWidth * currentPage.value) + 'px'
    ++currentPage.value
  }
}
const closeOtherLeft = () => {
  if (tabList.value.length > 1) {
    store.commit("SLICETAB", {
      index: 0,
      length: tabList.value.indexOf(defaultActive.value),
      service: store.state.user.currentService
    })
    getLeft()
  }

}
const closeOtherRight = () => {
  if (tabList.value.length > 1) {
    store.commit("SLICETAB", {
      index: tabList.value.indexOf(defaultActive.value) + 1,
      length: tabList.value.length,
      service: store.state.user.currentService
    })
    getLeft()
  }

}
const closeOther = () => {
  if (tabList.value.length > 1) {
    store.commit("SETTAB", {
      path: defaultActive.value,
      service: store.state.user.currentService
    })
    getLeft()
  }
}

const {
  isShowBindWechat,
  currentUserInfo,
  showWechatBindDialog,
  unbindWechatConfirm,
  isBindWechat
} = useBindWechat()

const _showWechatBindDialog = () => {
  const userInfo = store.state.user
  // console.log('userInfo', userInfo)
  showWechatBindDialog({ id: userInfo.userId })
}

const proactivePopBindWechat = ref(false)
watch(isBindWechat, (newValue) => {

  if (!newValue && !localStorage.getItem('isNoticeBindWx') && !store.state.user.bindWxPromptStatus) {
    localStorage.setItem('isNoticeBindWx', new Date().getTime() + '')
    proactivePopBindWechat.value = true
    _showWechatBindDialog()
  }
}, {
  immediate: true
})

const handleBindWechatFinished = () => {
  ElMessage.success('已成功绑定微信')
  isShowBindWechat.value = false
  // getStaffPageList()
  exit()
}
const tableData = ref([])
const props = {
  value: 'id',
  label: 'name',
  checkStrictly: true,
}
const getManagePageList = async () => {
  const rs = await queryTree({
    name: "",
    status: "",
  });
  if (rs.code == 200) {
    tableData.value = rs.payload;
  }
}

const isLianHai = ref(false)

const changeLogo = () => {
  if (process.env.NODE_ENV == 'production') {
    if (window.location.href.indexOf('lianhaikeji.com') != -1) {
      isLianHai.value = true
    } else {
      isLianHai.value = false
    }
  } else {
    isLianHai.value = true
  }
}

onBeforeMount(() => {
  changeLogo()
});

onMounted(() => {
  elementDiv.value = document.getElementById('func-tab-div')
  element.value = document.getElementById('func-tab')
  getLeft()
  getManagePageList()
})

</script>

<style scoped lang="scss">
.header {
  position: fixed;
  z-index: 2;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;
  background: #FFFFFF;
  padding: 0 16px;
  box-sizing: border-box;
  box-shadow: 0px 4px 10px 0px rgba(78, 89, 105, 0.06);

  .platform-logo {
    width: 224px;
    height: 24px;
    flex-shrink: 0;
    display: flex;
    align-items: center;

    img {
      width: 31.5px;
      height: 24px;
      padding-right: 10px;
      border-right: 1px solid #EEEFF1;
    }

    :deep(.el-cascader) {
      border: none;

      .el-input {
        border: none;
        font-weight: 600;
        color: #222637;

        .el-input__wrapper {
          box-shadow: none;

          .el-input__inner {
            font-weight: 600;
            color: #222637;
          }
        }
      }

      .icon-arrow-down:before {
        content: ''
      }
    }

  }

  .func-area {
    height: 50px;
    padding-top: 10px;
    border-right: 1px solid #E4E7ED;
    // width: calc(100vw - 240px - 204px);
    display: flex;
    align-items: center;
    flex-shrink: 0;
    flex-grow: 1;

    .func-btn {
      width: 24px;
      height: 24px;
      position: relative;
      margin-right: 10px;

      img {
        width: 24px;
        height: 24px;
      }

      &:hover {
        background: #F3F3F3;
      }

      .func-contextmenu {
        list-style: none;
        display: none;
        position: absolute;
        left: -69px;
        top: 24px;
        width: 138px;
        height: 152px;
        background: #FFFFFF;
        box-shadow: 0px 3px 14px 2px rgba(0, 0, 0, 0.05), 0px 8px 10px 1px rgba(0, 0, 0, 0.06), 0px 5px 5px -3px rgba(0, 0, 0, 0.1);
        border: 1px solid #DCDCDC;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #606266;
        text-align: center;

        li {
          color: #606266;
          line-height: 50px;

          &:hover {
            color: #0052D9;
          }
        }
      }

      &:hover {
        .func-contextmenu {
          display: block;
        }
      }
    }

    div.func-tab-div {
      width: calc(100% - 72px);
      height: 50px;
      position: relative;
      overflow: hidden;
    }

    ul.func-tab {
      height: 50px;
      list-style: none;
      display: flex;
      flex-wrap: nowrap;
      overflow-x: auto;
      position: absolute;
      left: 0;
      top: 0;

      li {
        flex-shrink: 0;
        width: 142px;
        margin-right: 4px;
        height: 50px;
        border-top: 2px solid #fff;
        background: #fff;
        position: relative;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #606266;
        display: flex;
        align-items: center;
        padding: 14px 20px;
        box-sizing: border-box;
        justify-content: space-between;
        transition: all .2s;
        -webkit-transition: all .2s;

        :deep(.el-icon) {
          color: #909399;

          &:hover {
            border-radius: 50%;
            color: #fff;
            background-color: #0052D9;
          }
        }

        p {
          width: 70px;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }

        &:hover {
          border-top-color: #C0C4CC;
          background: #F3F3F3;
        }

        &.active {
          color: #0052D9;
          border-top-color: #0052D9;
          background: #E8F2FF;
        }

        &::after {
          position: absolute;
          right: 0;
          top: 12px;
          content: ' ';
          width: 1px;
          height: 20px;
          background-color: #E4E7ED;
        }
      }
    }
  }

  .toolbar {
    height: 100%;
    padding-left: 16px;
    flex-shrink: 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    color: #412e2e;

    .tool-icon {
      margin-right: 6px;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      :deep(.el-icon) {
        font-size: 18px;
        color: #666;
      }
    }

    .tool-icon:hover {
      background-color: #4e59690f;
    }

    :deep(.el-dropdown) {
      height: 24px;
      display: flex;
      align-items: center;

      .el-dropdown-link {
        height: 24px;
        display: flex;
        align-items: center;
      }

      .el-icon {
        width: 24px;
        height: 24px;
      }
    }

    .tomerchant {
      margin: 18px;
      font-size: 30px;
    }

    .menu-center {
      display: flex;
      font-size: 14px;
      margin-right: 18px;
      height: 60px;
      line-height: 60px;

      &.active {
        border-bottom: 4px solid #3e61a9;
        height: 56px;
      }
    }

    .corp-name {
      font-size: 14px;
      margin-right: 26px;
      font-weight: 400;
    }

    .el-badge {
      margin-right: 20px;
      font-size: 14px;
      cursor: pointer;
    }

    .el-dropdown-link {
      color: #4E5969;
      cursor: pointer;
    }
  }
}

::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}
</style>
